package com.arm.service.impl;

import com.arm.dao.OrderMapper;
import com.arm.module.*;
import com.arm.service.*;
import com.arm.tools.DateUtil;
import com.arm.tools.GenerateID;
import com.arm.tools.json.JsonHandler;
import com.arm.tools.myRunTime.MyRunTimeExcption;
import com.google.gson.reflect.TypeToken;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;


/**
 * Created by baggio on 2016/12/27.
 */
@Service
public class OrderServiceImpl extends BaseService implements OrderService {


    @Autowired
    PaymentService paymentService;
    @Autowired
    OrderItemService orderItemService;


    @Autowired
    @Qualifier("weChatPayService")
    private PayService weChatPayService;

    @Autowired
    @Qualifier("backGroundPayService")
    private PayService backGroundPayService;

    @Autowired
    UserService userService;
    @Autowired
    ProductEntityService productEntityService;
    @Autowired
    ConsigneeInfoService consigneeInfoService;


    @Autowired
    OrderMapper orderMapper;


    @Transactional
    @Override
    public Order createOrder(String productJsons, User user, ConsigneeInfo consigneeInfo) {

        if (user == null) {
            throw new MyRunTimeExcption("用户不存在！");
        }
        if (user.getTid() == null) {
            throw new MyRunTimeExcption("用户Id不存在！");
        }
        if (consigneeInfo == null) {
            throw new MyRunTimeExcption("收货人地址不能为空！");
        }

//        if (StringUtils.isBlank(user.getUserName()) || StringUtils.isBlank(user.getPhone()) || StringUtils.isBlank(user.getUserAddress())) {
//            if (StringUtils.isBlank(consigneeInfo.getConsigneeName())) {
//                throw new MyRunTimeExcption("收货人姓名不能为空！");
//            }
//            if (StringUtils.isBlank(consigneeInfo.getConsigneePhone())) {
//                throw new MyRunTimeExcption("收货人电话不能为空！");
//            }
//            if (StringUtils.isBlank(consigneeInfo.getConsigneeAddress())) {
//                throw new MyRunTimeExcption("收货人地址不能为空！");
//            }
//            user.setUserName(consigneeInfo.getConsigneeName());
//            user.setPhone(consigneeInfo.getConsigneePhone());
//            user.setUserAddress(consigneeInfo.getConsigneeAddress());
//            userService.modifyUser(user);
//        }

        Long orderId = GenerateID.CreatetID();

        logger.info("【User：“+customerId+”====》createOrder====>OrderId :】" + orderId);
        logger.info("【User： :】" + user.toString());
        Order order = new Order();
        order.setOrderId(orderId);
        order.setStatus(OrderService.UNPAY);
        order.setCreateTime(new Date());


        Integer price = 0;
        order.setUserId(user.getTid());

        if (StringUtils.isBlank("productJsons")) {
            throw new MyRunTimeExcption("没有选择产品！");
        }

        List<Map<String, String>> productMapList = new ArrayList<>();
        logger.info("productJsons===>>"+productJsons);
        productMapList = JsonHandler.json2ObjList(productJsons, new TypeToken<List<Map<String, String>>>() {
        });

        List<OrderItem> orderItemList = new ArrayList<OrderItem>();
        System.out.println(productMapList.size());
        for (Map<String, String> productMap : productMapList) {
            String productEntityId = "";
            if (productMap.containsKey("productEntityId")) {
                productEntityId = productMap.get("productEntityId");
            }
            String amount = "";
            if (productMap.containsKey("amount")) {
                amount = productMap.get("amount");
            }

            OrderItem orderItem = orderItemService.createOrderItem(Long.parseLong(productEntityId), order, Integer.parseInt(amount));

            orderItemList.add(orderItem);
            price += orderItem.getPrice();

            order.setOrderItemList(orderItemList);


        }
        if (orderItemList.size() == 0) {
            logger.info("【Create OrderItem fail!】");
            throw new MyRunTimeExcption("创建订单失败！");
        }


        order.setOrderPrice(price);
        order.setUserId(user.getTid());
        orderMapper.insertOrder(order);

        consigneeInfo.setCreateTime(new Date());
        consigneeInfo.setOrderId(orderId);
        consigneeInfoService.modifyConsigneeInfo(consigneeInfo);
        return order;
    }

    @Override
    public Boolean cancelOrder(Long orderId) {
        logger.info("cancelOrder====>" + orderId);
        Order order = orderMapper.getOrderById(orderId);
        if (order == null) {
            throw new MyRunTimeExcption("订单号错误！");
        }

        order.setStatus(OrderService.CANCEL);
        orderMapper.updateOrderById(order);

        List<OrderItem> orderItemList = order.getOrderItemList();
        for (OrderItem orderItem : orderItemList) {
            orderItem.setStatus(OrderService.CANCEL);
            orderItemService.modifyOrderItem(orderItem);

        }
        return true;
    }


    @Override
    public Boolean modifyOrder(Order order) {
        orderMapper.updateOrderById(order);
        return true;
    }


    @Transactional
    @Override
    public PayParameter toPay(Long orderId, Payment payment, String remoteAddr, String openid) throws Exception {
        logger.info("【toPay====>orderId :】" + orderId);
        Order order = orderMapper.getOrderById(orderId);
        if (order == null) {
            throw new MyRunTimeExcption("订单没有找到");
        }
        if (order.getStatus() != OrderService.UNPAY) {
            throw new MyRunTimeExcption("订单状态不能完成支付");
        }

        if (DateUtil.hoursBetween(order.getCreateTime(), new Date()) > 24) {

            modifyOrderStatus(orderId, OrderService.OVER_TIME);
            throw new MyRunTimeExcption("订单操时！");

        }


        List<OrderItem> orderItemList = order.getOrderItemList();
        if (orderItemList == null || orderItemList.size() == 0) {
            throw new MyRunTimeExcption("订单项目没有找到");
        }
        Integer payPrice = 0;
        payment.setPayType(Payment.PAY_TYPE_PAY);
        payment.setStatus(OrderService.UNPAY);
        payment.setCreateTime(new Date());
        payPrice = payment.getPrice();
        paymentService.insertPayment(payment);


        if (payPrice.intValue() != order.getOrderPrice().intValue()) {
            logger.info(payPrice.intValue() + "<payPrice=======================orderPrice>" + order.getOrderPrice().intValue());
            throw new MyRunTimeExcption("payment价格错误");
        }

        // order.setPaymentList(paymentList);

        orderMapper.updateOrderById(order);


        PayService payService = getPayService(payment.getPayMode());
        Map<String, String> payParametersMap = new HashMap<>();

        payParametersMap.put("openid", openid);
        if(payService==null){
            throw new MyRunTimeExcption("支付出错!");
        }
        return payService.pay(String.valueOf(orderId), String.valueOf(payPrice), remoteAddr, payParametersMap);

    }

    private PayService getPayService(Byte payMode) {
        System.out.println("payMode==========================>>>>>" + payMode);
        if (payMode == Payment.PAY_MODE_WECHAT_BY_WECHATSET) {
            return weChatPayService;
        }
 /*       if (payMode == Payment.PAY_MODE_ALIPAY_BY_WECHATSET) {
            return aliPayService;
        }
        if (payMode == Payment.PAY_MODE_ALIPAY) {
            return aliPayService;
        }*/
        if (payMode == Payment.PAY_MODE_BACKGROUNDPAY) {
            return backGroundPayService;
        }
        return null;

    }

    @Override
    public Order getOrderById(Long orderId) {
        return orderMapper.getOrderById(orderId);
    }

    @Override
    public Order getOrder(Map<String, String> map) {
        return orderMapper.getOrder(map);
    }

    @Override
    public List<Order> getOrderList(Map<String, String> map) {

        return orderMapper.getOrderList(map);
    }

    @Override
    public List<Order> getOrderByUserId(Long userId) {
        return orderMapper.getOrderByUserId(userId);
    }

    @Override
    public Boolean modifyOrderStatus(Long orderId, Byte status) {
        Order order = orderMapper.getOrderById(orderId);
        order.setStatus(status);
        orderMapper.updateOrderById(order);
        return true;
    }

    @Override
    public Boolean closeOrder(Long orderId) {
        Order order = orderMapper.getOrderById(orderId);
        if (order == null) {
            throw new MyRunTimeExcption("订单没有找到！");
        }
        order.setStatus(OrderService.CLOSE);
        orderMapper.updateOrderById(order);
        return true;
    }

    @Override
    public Boolean completeOrder(Long orderId) {
        Order order = orderMapper.getOrderById(orderId);
        if (order == null) {
            throw new MyRunTimeExcption("订单没有找到！");
        }
        for (OrderItem orderItem : order.getOrderItemList()
                ) {

            orderItemService.modifyOrderItemStatus(orderItem.getOrderItemId(), OrderService.COMPELTEED);
        }
        order.setStatus(OrderService.CLOSE);
        orderMapper.updateOrderById(order);
        return true;
    }

    @Override
    public List<Map<String, String>> getDistributorOrderList(Map<String, String> map) {
        return orderMapper.getDistributorOrderList(map);
    }
}
